<template lang="pug">
  v-dialog(v-model="active" max-width="70vw" persistent)
    v-card
      v-card-title 订单出库
      v-card-text
        v-data-table( :headers="headers"
          v-model="selected"
          show-select
          :items="unLendedItems"
          loading-text="数据加载中..."
          no-data-text="未找到数据"
        )
      v-card-actions
        v-spacer
        v-btn(text @click="cancel") 取消
        v-btn(text color="primary" @click="confirm" :disabled="selected.length === 0") 出库
</template>

<script lang="ts">
  import Vue, {VueConstructor} from 'vue'
  import dialogMixin from '@/components/mixins/DialogMixin'
  import {mapActions, mapMutations, mapState} from 'vuex'
  import {OrderBundle, OrderItem} from '@/store/modules/types/Order'
  import {AxiosResponse} from 'axios'

  export default (Vue as VueConstructor<Vue & {
    orderItems: OrderItem[]

  }>).extend({
    name: 'order_lend_out',
    mixins: [dialogMixin],
    methods: {
      ...mapActions('order', ['lendOrderItems']),
      ...mapMutations('order', ['setOrderItems', 'setOrderBundles']),
      toggle() {
        this.active = !this.active
        this.selected = []
      },
      confirm() {
        this.$confirm({
          body: '是否确定订单出库？'
        }).then(() => {
          this.$loading('保存中...')
          return this.lendOrderItems({
            'ids': this.selected.map(x => x.id)
          })
        }).then((response: AxiosResponse) => {
          this.setOrderItems(response.data.orderItems)
          this.setOrderBundles(response.data.orderBundles)
          this.toggle()
        }).finally(this.$loading.close)
      }
    },
    computed: {
      ...mapState('order', ['orderItems', 'orderBundles']),
      unLendedItems() {
        let unLendBundles = this.orderBundles
            .filter((bundle: OrderBundle) => !bundle.rental_out_at)
            .map((bundle: OrderBundle) => ({ id: `bundle_${bundle.id}`, name: `[组合] ${bundle.name}` }))
        let unLendItems = this.orderItems.filter((item: OrderItem) => !item.rental_out_at)
        return unLendBundles.concat(unLendItems)
      }
    },
    data() {
      return {
        selected: [],
        headers: [
          { text: '名称', value: 'name' },
        ]
      }
    }
  })
</script>